package com.lingnan.wanxiangxinxun.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingnan.wanxiangxinxun.entity.dto.EmployeeDTO;
import com.lingnan.wanxiangxinxun.entity.po.Authority;
import com.lingnan.wanxiangxinxun.entity.po.EmpPositionAuthority;
import com.lingnan.wanxiangxinxun.entity.po.Employee;
import com.lingnan.wanxiangxinxun.entity.vo.common.PageVO;
import com.lingnan.wanxiangxinxun.entity.vo.service.AuthorityVO;
import com.lingnan.wanxiangxinxun.mapper.AuthorityMapper;
import com.lingnan.wanxiangxinxun.mapper.EmployeeMapper;
import com.lingnan.wanxiangxinxun.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.web.config.QuerydslWebConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工表 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-03-13
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private AuthorityMapper authorityMapper;


    //修改某个职位的权限
    @Override
    @Transactional
    public void updateAuthority(Integer positionId, List<Integer> authorityIds) {
        // 1、查找这个职位拥有的全部权限
        List<EmpPositionAuthority> AuthorityList = employeeMapper.getPositionAuthority(positionId);

        // 2、先删除这个职位的所有权限（现有的全部权限置为-1）
        employeeMapper.setPositionAuthority(positionId, -1);

        int diff = authorityIds.size() - AuthorityList.size();
        // 3、根据传入的authorityIds设置新的权限
        for(int i = 0; i < authorityIds.size() && i < AuthorityList.size(); i++){
            int id = AuthorityList.get(i).getId();
            employeeMapper.updatePositionAuthority(id, authorityIds.get(i));
        }
        if(diff > 0){ // 如果传入的权限数量大于已有的权限数量，说明有新的权限需要添加 (小于的情况不用管，多的会被第四步删掉)
            for(int i = AuthorityList.size(); i < authorityIds.size(); i++){
                EmpPositionAuthority epa = new EmpPositionAuthority();
                epa.setPositionId(positionId);
                epa.setAuthorityId(authorityIds.get(i));
                employeeMapper.insertAuthority(epa);
            }
        }

        // 4、删除权限为-1的职位权限
        employeeMapper.delAuthority(-1);
    }

    @Override
    public PageVO<Employee> getAllInPage(long current, long size) {
        Page<Employee> page_MP = this.page(new Page<>(current, size));

        return PageVO.of(page_MP);
    }

    @Override
    public PageVO<Employee> getInCondition(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        long current = employeeDTO.getCurrent();
        long size = employeeDTO.getSize();

        Page<Employee> page = new Page<>(current, size); // 创建分页对象
        Page<Employee> page_MP = lambdaQuery()
                .eq(employee.getId() != null, Employee::getId, employee.getId())
                .like(employee.getName() != null, Employee::getName, employee.getName())
                .eq(employee.getPosition() != null, Employee::getPosition, employee.getPosition())
                .eq(employee.getPassword() != null, Employee::getPassword, employee.getPassword())
                .eq(employee.getStatus() != null, Employee::getStatus, employee.getStatus())

                .page(page); // 应用分页

        return PageVO.of(page_MP);
    }


    //查找--根据id查询
    @Override
    public List<Employee> getEmployeeListByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()){
            return null;
        }
        return employeeMapper.getEmployeeListByIds(ids);
    }


    //查找--员工登录
    @Override
    public Employee empSignIn(Integer id, String password) {
        Wrapper<Employee> queryWrapper = lambdaQuery()
                .eq(Employee::getId, id)
                .eq(Employee::getPassword, password)
                .getWrapper();
        return getOne(queryWrapper);
    }

    //查找--员工权限
    @Override
    public List<AuthorityVO> getAuthority(Integer id) {
        List<Authority> AllAuthorityList = employeeMapper.getAuthority(id);
        List<Authority> aList_hasParent = new ArrayList<>();
        List<Authority> aList_NoParent = new ArrayList<>();
        //提取出有父菜单的和没有父菜单的
        for (Authority a : AllAuthorityList) {
            if (a.getParentId() != null) {
                aList_hasParent.add(a); //有父菜单的
            }else {
                aList_NoParent.add(a); //没有父菜单的
            }
        }

        /*
          1.如果有子菜单，而且找到了父菜单，那么返回的时候，把子菜单放在父菜单的children中
          2.如果有子菜单，但是找不到父菜单，那也要返回这个子菜单
         */
        List<AuthorityVO> VOList = new ArrayList<>();
        // 1.首先处理没有父菜单的项（这些可能是父菜单或独立菜单）
        for (Authority a_np : aList_NoParent) {
            AuthorityVO av = new AuthorityVO();
            BeanUtils.copyProperties(a_np, av);
            av.setChildren(new ArrayList<>());

            //看看它是否有子菜单，有就添加
            for (Authority a_hp : aList_hasParent) {
                if (Objects.equals(a_hp.getParentId(), a_np.getId())) {
                    AuthorityVO av1 = new AuthorityVO();
                    BeanUtils.copyProperties(a_hp, av1);
                    av.getChildren().add(av1); // 添加children
                }
            }
            VOList.add(av);
        }
        // 2.处理那些有父菜单但父菜单不存在的项（孤儿子菜单），因为有时候只想返回一个父菜单下面的个别子菜单
        for (Authority a_hp : aList_hasParent) {
            boolean parentExists = false;
            for (AuthorityVO vo : VOList) {
                if (vo.getId().equals(a_hp.getParentId())) {
                    parentExists = true; // 该菜单的父菜单存在
                    break;
                }
            }
            if (!parentExists) {
                // 父菜单不存在，直接作为独立菜单添加
                AuthorityVO a_vo = new AuthorityVO();
                BeanUtils.copyProperties(a_hp, a_vo);
                a_vo.setChildren(new ArrayList<>());
                VOList.add(a_vo);
            }
        }

        return VOList;
    }

    //查找--所有权限
    @Override
    public List<Authority> getAllAuthority() {
        return authorityMapper.selectList(null);
    }

    //查找--员工权限(用于修改权限)
    @Override
    public List<Authority> getPositionAuthority(Integer id) {
        List<Authority> authorityList;
        List<EmpPositionAuthority> epaList = employeeMapper.getPositionAuthority(id);
        // 提取epaList的AuthorityId属性
        List<Integer> idList = epaList.stream()
                .map(EmpPositionAuthority::getAuthorityId)
                .toList();

        QueryWrapper<Authority> qw = new QueryWrapper<>();
        qw.in("id", idList);
        qw.orderByAsc("active_menu");
        authorityList = authorityMapper.selectList(qw);

        return authorityList;
    }
}
